package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

//        从exchange中获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

//        如果是登录请求时 应该直接放行
        String path = request.getURI().getPath(); // login/in
        if(path.contains("/login")){
            return chain.filter(exchange);
        }

//        判断请求中是否有token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isBlank(token)){ //如果token为空 返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        判断token的合法性
//        看是否能从token中解析出用户数据 id name
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int type = AppJwtUtil.verifyToken(claimsBody);
            if(type==-1||type==0){  //代表token是有效
//                从claimsBody获取id和name放到请求头中
                Long id = claimsBody.get("userId",Long.class);
                String name = claimsBody.get("name",String.class);
                request.mutate().header("userId",id.toString());
                request.mutate().header("name",name);
                return chain.filter(exchange);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
//        解析token获取用户id 放到请求头中
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
